package leetcode.code0468;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	String nan = "Neither";

	public String validIPAddress(String queryIP) {
		if (queryIP == null) {
			return nan;
		}
		if (queryIP.contains(".") && !queryIP.contains(":")) {
			return this.ipv4(queryIP);
		}
		if (!queryIP.contains(".") && queryIP.contains(":")) {
			return this.ipv6(queryIP);
		}
		return nan;
	}

	private String ipv6(String queryIP) {
		if (queryIP.charAt(0) == ':' || queryIP.charAt(queryIP.length() - 1) == ':') {
			return nan;
		}
		String[] numStrs = queryIP.split(":");
		if (numStrs.length != 8) {
			return nan;
		}
		for (String numStr : numStrs) {
			if (numStr.length() > 4 || numStr.length() == 0) {
				return nan;
			}
			for (int i = 0; i < numStr.length(); i++) {
				char cur = numStr.charAt(i);
				if ((cur < '0' || cur > '9') && (cur < 'a' || cur > 'f') && (cur < 'A' || cur > 'F')) {
					return nan;
				}
			}
		}
		return "IPv6";
	}

	private String ipv4(String queryIP) {
		if (queryIP.charAt(0) == '.' || queryIP.charAt(queryIP.length() - 1) == '.') {
			return nan;
		}
		String[] numStrs = queryIP.split("[.]");
		if (numStrs.length != 4) {
			return nan;
		}
		for (String numStr : numStrs) {
			if (numStr.length() > 3 || numStr.length() == 0) {
				return nan;
			}
			int num = 0;
			for (int i = 0; i < numStr.length(); i++) {
				char cur = numStr.charAt(i);
				if (cur < '0' || cur > '9') {
					return nan;
				}
				int curNum = cur - '0';
				if (curNum == 0 && num == 0 && numStr.length() > 1) {// 前导0
					return nan;
				}
				num = num * 10 + curNum;
			}
			if (num > 255) {
				return nan;
			}
		}
		return "IPv4";
	}

	@Override
	public void debug1() {
		HelpDebug.compare("IPv4", this.validIPAddress("192.0.0.1"));
		HelpDebug.compare("Neither", this.validIPAddress("12..33.4"));
		HelpDebug.compare("IPv4", this.validIPAddress("172.16.254.1"));
		HelpDebug.compare("Neither", this.validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334:"));
	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
